## Script to patch up diff created by `repo diff`
# https://blog.chenjia.me/articles/160316-163205.html
#

## Script to patch up diff created by `repo diff`
# https://blog.chenjia.me/articles/160316-163205.html

if [ -z "$1" ] || [ ! -e "$1" ]; then
  printf "接受 'repo diff' 生成的补丁。\n\n"
  printf "Usages: \n\t%s <repo_diff_file>\n" "$0"
  exit 0
fi

rm -fr _tmp_splits*
cat "$1" | csplit -qf '' -b "_tmp_splits.%d.diff" - '/^project.*\/$/' '{*}'

working_dir=$(pwd)

for proj_diff in _tmp_splits.*.diff; do
  chg_dir=$(grep '^project.*/$' "$proj_diff" | cut -d " " -f 2)
  echo "FILE: $proj_diff $chg_dir"
  if [ -e "$chg_dir" ]; then
    (
      cd "$chg_dir" || exit

      grep -v '^project.*/$' "$working_dir"/"$proj_diff" | patch -Np1
    )
  else
    # TODO: add warning tag color yellow
    echo "$0: Project directory $chg_dir don't exists."
  fi
done
